#!/usr/bin/env python3
"""手机播放列表功能处理器"""

import asyncio
from aiohttp import web
from embytools.emby_client import EmbyClient

async def create_phone_playlist_handler(request, emby_client: EmbyClient):
    """为媒体库创建或删除手机播放列表"""
    try:
        data = await request.json()
        library_id = data.get('library_id')
        library_name = data.get('library_name')
        action = data.get('action', 'enable')  # enable 或 disable
        
        if not library_id or not library_name:
            return web.json_response({
                'success': False,
                'error': '缺少必要参数'
            }, status=400)
        
        # 创建播放列表名称
        playlist_name = f"{library_name} - 手机版"
        
        if action == 'enable':
            # 检查播放列表是否已存在
            playlist_exists = await emby_client.check_playlist_exists(playlist_name)
            if playlist_exists:
                return web.json_response({
                    'success': True,
                    'playlist_name': playlist_name,
                    'action': 'already_enabled',
                    'message': f'媒体库"{library_name}"的手机播放列表已存在'
                })
            
            # 获取或创建播放列表
            playlist = await emby_client.get_or_create_playlist(playlist_name)
            if not playlist:
                return web.json_response({
                    'success': False,
                    'error': '创建播放列表失败'
                }, status=500)
            
            # 扫描媒体库中的竖屏视频
            added_count = 0
            skipped_count = 0
            start_index = 0
            page_size = 100
            
            while True:
                try:
                    # 搜索媒体库项目
                    search_result = await emby_client.search_items(
                        library_id=library_id,
                        start_index=start_index,
                        limit=page_size
                    )
                    
                    if not search_result.items:
                        break
                    
                    # 筛选竖屏视频（宽小于高）
                    portrait_videos = []
                    for item in search_result.items:
                        if (hasattr(item, 'width') and hasattr(item, 'height') and 
                            item.width and item.height and item.width < item.height):
                            portrait_videos.append(item.id)
                    
                    # 获取播放列表现有项目
                    existing_items = await emby_client.get_playlist_items(playlist.id, limit=1000)
                    existing_ids = {item.id for item in existing_items}
                    
                    # 过滤掉已存在的项目
                    new_items = [item_id for item_id in portrait_videos if item_id not in existing_ids]
                    
                    # 添加到播放列表
                    if new_items:
                        success = await emby_client.add_items_to_playlist(playlist.id, new_items)
                        if success:
                            added_count += len(new_items)
                        else:
                            print(f"添加项目失败: {new_items}")
                    
                    skipped_count += len(portrait_videos) - len(new_items)
                    
                    # 检查是否还有更多项目
                    if len(search_result.items) < page_size:
                        break
                    
                    start_index += page_size
                    
                except Exception as e:
                    print(f"处理媒体库项目时出错: {e}")
                    break
            
            return web.json_response({
                'success': True,
                'playlist_name': playlist_name,
                'playlist_id': playlist.id,
                'added_count': added_count,
                'skipped_count': skipped_count,
                'action': 'enabled',
                'message': f'成功为媒体库"{library_name}"创建手机播放列表，新增{added_count}个竖屏视频，跳过{skipped_count}个已存在视频'
            })
        
        elif action == 'disable':
            # 查找并删除播放列表
            playlist = await emby_client.get_playlist_by_name(playlist_name)
            if playlist:
                success = await emby_client.delete_playlist(playlist.id)
                if success:
                    return web.json_response({
                        'success': True,
                        'action': 'disabled',
                        'message': f'已删除媒体库"{library_name}"的手机播放列表'
                    })
                else:
                    return web.json_response({
                        'success': False,
                        'error': '删除播放列表失败'
                    }, status=500)
            else:
                return web.json_response({
                    'success': True,
                    'action': 'already_disabled',
                    'message': f'媒体库"{library_name}"的手机播放列表不存在'
                })
        
    except Exception as e:
        return web.json_response({
            'success': False,
            'error': str(e)
        }, status=500)